import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

axios.defaults.withCredentials = true

// create an axios instance
const service = axios.create({
  // baseURL: "127.0.0.1",
  baseURL: process.env.VUE_APP_BASE_API,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
  timeout: 300000 // request timeout
})
// console.log(service)
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (sessionStorage.getItem('token')) {
      config.headers['X-Token'] = sessionStorage.getItem('token')
    }
    /* if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    } */
    config.baseURL = config.port ? (config.baseURL + ":" + config.port) : config.baseURL
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    // console.log('err' + error) // for debug
    Message({
      message: '服务异常',
      type: 'error',
      duration: 5 * 1000
    })
  }
)

export default service
